package com.nwpu.intimacy.user;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nwpu.intimacy.R;
import com.nwpu.intimacy.main.MainActivity;
import com.nwpu.intimacy.utils.CacheUtil;

public class UserInformationActivity extends Activity {

	private static final String URL = "http://10.128.51.203:8080/SoftwareEngineer/modify";

	private SharedPreferences sp_userMessage;

	private ImageView user_header;
	private TextView user_username;
	private TextView user_location;
	private TextView user_sex;
	private TextView user_homeTown;
	private TextView user_comment;

	private RelativeLayout relativeLayout_first;
	private RelativeLayout relativeLayout_one;
	private RelativeLayout relativeLayout_two;
	private RelativeLayout relativeLayout_three;
	private RelativeLayout relativeLayout_four;
	private RelativeLayout relativeLayout_five;
	private RelativeLayout relativeLayout_six;

	private static final int IMAGE_REQUEST_CODE = 0;
	private static final int CAMERA_REQUEST_CODE = 1;
	private static final int RESIZE_REQUEST_CODE = 2;
	private final static int USER_MODIFY_PHOTO_SUCCESS = 0x114;
	private final static int USER_MODIFY_FAIL = 0x115;
	private final static int USER_MODIFY_SEX_SUCCESS = 0x116;

	private Handler modifyHandler;

	private static final String IMAGE_FILE_NAME = "header.jpg";

	private Bitmap photo;

	private int sex_int;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_userinformation);

		sp_userMessage = this.getSharedPreferences("userMessage",
				Context.MODE_PRIVATE);

		initLayout();
		setUserHeader();

		user_username.setText(sp_userMessage.getString("USER_NAME", ""));

		String area_str = sp_userMessage.getString("AREA", "");
		String[] strarray = area_str.split(";", 2);
		user_homeTown.setText(strarray[1]);

		user_comment.setText(sp_userMessage.getString("COMMENT", ""));

		int sex_str = sp_userMessage.getInt("SEX", 0);

		if (sex_str == 0) {

			user_sex.setText("Secret");
			sex_int = 0;

		} else if (sex_str == 1) {

			user_sex.setText("Male");
			sex_int = 1;

		} else if (sex_str == 2) {

			user_sex.setText("Female");
			sex_int = 2;

		}

		relativeLayout_first.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Toast.makeText(getApplicationContext(), "Replace picture",
						Toast.LENGTH_SHORT).show();

			}
		});

		relativeLayout_two.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), QRCodeActivity.class);

				startActivity(intent);

			}
		});

		relativeLayout_four.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				sexDialog();

			}
		});

		relativeLayout_five.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Dialog dialog = new HometownModifyDialog(
						UserInformationActivity.this);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.getWindow().setBackgroundDrawable(new BitmapDrawable());
				dialog.show();

				WindowManager windowManager = getWindowManager();
				WindowManager.LayoutParams windowParams = dialog.getWindow()
						.getAttributes();
				Display d = windowManager.getDefaultDisplay(); // 获取屏幕宽度和高度
				windowParams.width = (int) (d.getWidth() * 0.9); // 设置宽度
				windowParams.height = (int) (d.getHeight() * 0.75); // 设置高度
				dialog.getWindow().setAttributes(windowParams);

			}
		});

		relativeLayout_six.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent();
				intent.setClass(getApplicationContext(),
						ModifyInformationActivity.class);

				startActivity(intent);
				finish();

			}
		});

		user_header.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				onImageChoiceDialog();

			}
		});

		// 线程交互
		modifyHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case USER_MODIFY_PHOTO_SUCCESS: {

					try {
						CacheUtil.WriteToFile(
								sp_userMessage.getString("USER_NAME", ""),
								photo, "Photo");

						Toast.makeText(getApplicationContext(), "修改成功!",
								Toast.LENGTH_SHORT).show();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					break;
				}
				case USER_MODIFY_SEX_SUCCESS: {

					Toast.makeText(getApplicationContext(), "性别修改成功!",
							Toast.LENGTH_SHORT).show();

					if (sex_int == 0) {

						user_sex.setText("Sercet");

					} else if (sex_int == 1) {

						user_sex.setText("Male");

					} else if (sex_int == 2) {

						user_sex.setText("Female");

					}

					break;

				}
				case USER_MODIFY_FAIL: {

					Toast.makeText(getApplicationContext(), "修改错误!",
							Toast.LENGTH_SHORT).show();

				}
				default:
					super.handleMessage(msg);
				}
			}

		};

	}

	// 初始化所有控件
	public void initLayout() {

		relativeLayout_first = (RelativeLayout) findViewById(R.id.user_header_R);
		relativeLayout_one = (RelativeLayout) findViewById(R.id.R_first);
		relativeLayout_two = (RelativeLayout) findViewById(R.id.R_second);
		relativeLayout_three = (RelativeLayout) findViewById(R.id.R_third);
		relativeLayout_four = (RelativeLayout) findViewById(R.id.R_fourth);
		relativeLayout_five = (RelativeLayout) findViewById(R.id.R_five);
		relativeLayout_six = (RelativeLayout) findViewById(R.id.R_six);
		user_header = (ImageView) findViewById(R.id.image_user_userinformation);
		user_username = (TextView) findViewById(R.id.user_username);
		user_location = (TextView) findViewById(R.id.location_userinformation);
		user_sex = (TextView) findViewById(R.id.sex_userinformation);
		user_homeTown = (TextView) findViewById(R.id.hometown_userinformation);
		user_comment = (TextView) findViewById(R.id.comment_userinformation);

	}

	/**
	 * 设置用户头像
	 */
	public void setUserHeader() {

		Bitmap photo = CacheUtil.GetFromFile(
				sp_userMessage.getString("USER_NAME", ""), "Photo");
		Drawable drawable = new BitmapDrawable(photo);
		user_header.setImageDrawable(drawable);

	}

	/**
	 * 修改该用户头像
	 */
	private void onImageChoiceDialog() {

		new AlertDialog.Builder(this)
				.setTitle("Set Profile Photo")
				.setItems(
						new String[] { "Choose from a mobile photo album",
								"Photograph" },
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								switch (which) {
								case 0:

									Intent galleryIntent = new Intent(
											Intent.ACTION_GET_CONTENT);
									galleryIntent
											.addCategory(Intent.CATEGORY_OPENABLE);
									galleryIntent.setType("image/*");
									startActivityForResult(galleryIntent,
											IMAGE_REQUEST_CODE);

									break;
								case 1:

									if (isSdcardExisting()) {
										Intent cameraIntent = new Intent(
												"android.media.action.IMAGE_CAPTURE");
										cameraIntent.putExtra(
												MediaStore.EXTRA_OUTPUT,
												getImageUri());
										cameraIntent.putExtra(
												MediaStore.EXTRA_VIDEO_QUALITY,
												0);
										startActivityForResult(cameraIntent,
												CAMERA_REQUEST_CODE);
									} else {
										Toast.makeText(getApplicationContext(),
												"Please insert the sd card!",
												Toast.LENGTH_LONG).show();
									}

									break;

								}

							}
						}

				).show();

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		} else {
			switch (requestCode) {
			case IMAGE_REQUEST_CODE:
				resizeImage(data.getData());
				break;
			case CAMERA_REQUEST_CODE:
				if (isSdcardExisting()) {
					resizeImage(getImageUri());
				} else {
					Toast.makeText(UserInformationActivity.this,
							"Memory card not found, you can not store photos!",
							Toast.LENGTH_LONG).show();
				}
				break;

			case RESIZE_REQUEST_CODE:
				if (data != null) {
					showResizeImage(data);
				}
				break;
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private boolean isSdcardExisting() {
		final String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	public void resizeImage(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 150);
		intent.putExtra("outputY", 150);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, RESIZE_REQUEST_CODE);
	}

	private void showResizeImage(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			try {
				photo = extras.getParcelable("data");
				Drawable drawable = new BitmapDrawable(photo);
				user_header.setImageDrawable(drawable);

				onModify(photo);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private Uri getImageUri() {
		return Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
				IMAGE_FILE_NAME));
	}

	// 判断用户修改信息类型，并向服务器发送请求
	public void onModify(final Bitmap photo) {

		new Thread() {

			public void run() {

				try {

					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					jsonObject.put("username",
							sp_userMessage.getString("USER_NAME", ""));
					jsonObject.put("password",
							sp_userMessage.getString("PASSWORD", ""));
					jsonObject.put("portrait", bitmaptoString(photo));

					jsonObject.put("sex", sp_userMessage.getInt("SEX", 0));
					jsonObject.put("comment",
							sp_userMessage.getString("COMMENT", ""));
					jsonObject
							.put("area", sp_userMessage.getString("AREA", ""));

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					Log.e("login data", jsonArray.toString());

					HttpPost httpPost = new HttpPost(URL);

					// 设置参数，仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair("modify",
							jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							"UTF_8"));

					HttpResponse httpResponse = client.execute(httpPost);

					String result = EntityUtils.toString(
							httpResponse.getEntity(), HTTP.UTF_8);

					/*
					 * String result = new String(
					 * EntityUtils.toString(httpResponse.getEntity()),
					 * HTTP.UTF_8);
					 */

					Log.e("result", result);
					Log.e("hkq", URLDecoder.decode(result, HTTP.UTF_8));
					JSONArray jsonArray2 = new JSONArray(result);
					JSONObject jsonObject2 = (JSONObject) jsonArray2.get(0);

					if (jsonObject2.optString("result").equals("success")) {

						Message msg = new Message();
						msg.what = USER_MODIFY_PHOTO_SUCCESS;
						msg.obj = result;
						modifyHandler.sendMessage(msg);

					} else {

						Message msg = new Message();
						msg.what = USER_MODIFY_FAIL;
						msg.obj = result;
						modifyHandler.sendMessage(msg);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}.start();

	}

	/**
	 * 将Bitmap格式图片转化为字符串
	 * 
	 * @param bitmap
	 * @return
	 */
	public String bitmaptoString(Bitmap bitmap) {

		// 将Bitmap转换成字符串
		String string = null;
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.PNG, 100, bStream);
		byte[] bytes = bStream.toByteArray();
		string = Base64.encodeToString(bytes, Base64.DEFAULT);
		return string;
	}

	/**
	 * 点击后退键效果
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:

			setResult(Activity.RESULT_OK);
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), MainActivity.class);
			intent.putExtra("setPosition", 3);
			startActivity(intent);

			finish();

		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void sexDialog() {

		AlertDialog.Builder builder = new AlertDialog.Builder(
				UserInformationActivity.this);
		builder.setIcon(R.drawable.ic_launcher);
		builder.setTitle("Sex Choose");
		final String[] sex = { "Male", "Female", "Secret" };

		int i = 0;

		int sex_str = sp_userMessage.getInt("SEX", 0);
		if (sex_str == 0) {

			i = 2;

		} else if (sex_str == 1) {

			i = 0;

		} else if (sex_str == 2) {

			i = 1;

		}

		final int sexInt[] = { sex_int };

		// 设置一个单项选择下拉框
		/**
		 * 第一个参数指定我们要显示的一组下拉单选框的数据集合 第二个参数代表索引，指定默认哪一个单选框被勾选上，1表示默认'女' 会被勾选上
		 * 第三个参数给每一个单选项绑定一个监听器
		 */
		builder.setSingleChoiceItems(sex, i,
				new DialogInterface.OnClickListener() {
					@SuppressWarnings("null")
					@Override
					public void onClick(DialogInterface dialog, int which) {

						sexInt[0] = which;

					}
				});
		builder.setPositiveButton("Submit",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

						if (sexInt[0] == 0) {

							sex_int = 1;
							onModify_Sex(1);

						} else if (sexInt[0] == 1) {

							sex_int = 2;
							onModify_Sex(2);

						} else if (sexInt[0] == 2) {

							sex_int = 0;
							onModify_Sex(0);

						}

					}
				});
		builder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

						dialog.dismiss();

					}
				});
		builder.show();

	}

	public void onModify_Sex(final int modifySex) {

		new Thread() {

			public void run() {

				try {

					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = new JSONObject();

					Bitmap photo = CacheUtil.GetFromFile(
							sp_userMessage.getString("USER_NAME", ""), "Photo");

					jsonObject.put("username",
							sp_userMessage.getString("USER_NAME", ""));
					jsonObject.put("password",
							sp_userMessage.getString("PASSWORD", ""));
					jsonObject.put("portrait", bitmaptoString(photo));

					jsonObject.put("sex", modifySex);
					jsonObject.put("comment",
							sp_userMessage.getString("COMMENT", ""));
					jsonObject
							.put("area", sp_userMessage.getString("AREA", ""));

					jsonArray.put(jsonObject);

					HttpClient client = new DefaultHttpClient();

					Log.e("login data", jsonArray.toString());

					HttpPost httpPost = new HttpPost(URL);

					// 设置参数，仿html表单提交
					List<NameValuePair> paramList = new ArrayList<NameValuePair>();
					BasicNameValuePair param = new BasicNameValuePair("modify",
							jsonArray + "");
					paramList.add(param);

					httpPost.setEntity(new UrlEncodedFormEntity(paramList,
							"UTF_8"));

					HttpResponse httpResponse = client.execute(httpPost);

					String result = EntityUtils.toString(
							httpResponse.getEntity(), HTTP.UTF_8);

					/*
					 * String result = new String(
					 * EntityUtils.toString(httpResponse.getEntity()),
					 * HTTP.UTF_8);
					 */

					Log.e("result", result);
					Log.e("hkq", URLDecoder.decode(result, HTTP.UTF_8));
					JSONArray jsonArray2 = new JSONArray(result);
					JSONObject jsonObject2 = (JSONObject) jsonArray2.get(0);

					if (jsonObject2.optString("result").equals("success")) {

						sp_userMessage.edit().putInt("SEX", modifySex).commit();
						Message msg = new Message();
						msg.what = USER_MODIFY_SEX_SUCCESS;
						msg.obj = result;
						modifyHandler.sendMessage(msg);

					} else {

						Message msg = new Message();
						msg.what = USER_MODIFY_FAIL;
						msg.obj = result;
						modifyHandler.sendMessage(msg);

					}

				} catch (JSONException e) {
					e.printStackTrace();
				} catch (MalformedURLException e1) {
					e1.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}.start();

	}
}
